package com.itheima.service.impl;


import com.itheima.bean.exception.BusinessException;
import com.itheima.bean.pojo.User;
import com.itheima.bean.vo.AddUser;
import com.itheima.bean.vo.Code;
import com.itheima.bean.vo.PageBean;
import com.itheima.bean.vo.Pagination;
import com.itheima.dao.UserDao;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 分页查询用户数据
     *
     * @param pagination 分页对象
     * @return
     */
    public PageBean queryUserByPage(Pagination pagination) {
        if (pagination == null) {
            throw new RuntimeException("参数为空");
        }
        if (pagination.getSearch() == null) {
            return getUserPageBean(pagination);
        } else {
            return getUserPageBeanBySearch(pagination);
        }

    }

    private PageBean getUserPageBeanBySearch(Pagination pagination) {
        Integer currentPage = pagination.getCurrentPage();
        Integer pageSize = pagination.getPageSize();
        String search = pagination.getSearch();
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        //计算起始索引
        Integer index = (currentPage - 1) * pageSize;
        //调用DAO层分页查询
        List<User> userList = userDao.selectUserByPageAndUserName(index, pageSize, search);
        //调用dao层功能，查询总记录数
        int count = userDao.findCountByUserName(search);
        PageBean<User> pageBean = null;
        if (userList != null & !userList.isEmpty()) {
            pageBean = new PageBean<>();
            pageBean.setRows(userList);
            pageBean.setTotal(count);
        }

        return pageBean;
    }

    private PageBean<User> getUserPageBean(Pagination pagination) {
        Integer currentPage = pagination.getCurrentPage();
        Integer pageSize = pagination.getPageSize();

        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }

        //模拟未知异常
        // int i = 1 / 0;
        //计算起始索引
        Integer index = (currentPage - 1) * pageSize;
        //调用DAO层分页查询
        List<User> userList = userDao.findUserByPage(index, pageSize);
        //调用dao层功能，查询总记录数
        int count = userDao.findCount();
        //分页查询bean对象
        PageBean<User> pageBean = null;
        if (userList != null & !userList.isEmpty()) {
            pageBean = new PageBean<>();
            pageBean.setRows(userList);
            pageBean.setTotal(count);
        }

        return pageBean;
    }


    /**
     * 添加用户及角色
     *
     * @param user
     * @return
     */
    @Override
    public boolean addUserAndRole(AddUser user) {
        if (user == null) {
            throw new RuntimeException("参数为空");
        }
        //添加用户
        boolean saveResult = saveUser(user);

        //添加用户角色
        if (saveResult) {
            saveUserRole(user.getId(), user.getRoleIds());
        }
        return true;
    }

    //添加用户
    public boolean saveUser(AddUser user) {
        //调用dao层添加用户
        int result = userDao.addUser(user);
        return result > 0 ? true : false;
    }

    //添加用户角色
    public boolean saveUserRole(Integer userId, List<String> roleIds) {
        //业务逻辑判断：传递参数的合法性（用户录入）
        if (userId < 0) {
            //业务异常: 用户造成的
            throw new BusinessException(Code.BUSINESS_ERR, "用户id不能为负数");
        }
        //调用dao层添加用户角色,一个用户可以多个角色，循环
        int result = -1;
        for (String roleId : roleIds) {
            result = userDao.addUserRole(userId, Integer.parseInt(roleId));
        }

        return result > 0 ? true : false;
    }

    //TODO：删除用户
    @Override
    public boolean deleteUser(Integer uid) {
        if (uid <= 0) {
            throw new BusinessException(Code.BUSINESS_ERR, "id不能为负数！");
        }
        //删除用户id
        boolean result = userDao.deleteRoleByUid(uid);
        if (result) {
            //删除用户对应的角色
            userDao.deleteUserById(uid);
        }

        return true;
    }

    //TODO：修改用户
    @Override
    public boolean updateUser(AddUser addUser) {
        if (addUser == null) {
            throw new RuntimeException("数据为空！");
        }
        //修改用户的基本数据（用户表）
        boolean result = userDao.updateUser(addUser);
        //删除用户的所有角色数据
        Integer uid = addUser.getId();
        userDao.deleteRoleByUid(uid);
        // 添加用户的角色数据 （用户角色表）
        List<String> roleIds = addUser.getRoleIds();
        for (String roleId : roleIds) {
            userDao.addRoleByUser(uid, roleId);
        }
        return true;
    }
}
